<template>
  <div class="comment-post">
    <van-field
      class="post-field"
      v-model.trim="message"
      rows="2"
      autosize
      type="textarea"
      maxlength="50"
      placeholder="请输入留言"
      show-word-limit
    />
    <van-button
      class="post-btn"
      :disabled='!message'
      @click="publishCommentFn"
    >发布</van-button>
  </div>
</template>

<script>
import { publishComment } from '@/api/comment.js'
export default {
  name: 'CommentPost',
  components: {},
  props: {
    // 评论的目标ID --->文章ID或 评论ID
    target: {
      type: [String, Number, Object],
      required: true
    },
    // 文章ID
    artId: {
      type: [String, Number, Object],
      // 默认显示为null 不传也显示null
      default: null
    }
  },
  data () {
    return {
      // 评论的内容
      message: ''
    }
  },
  computed: {},
  watch: {},
  created () { },
  mounted () { },
  methods: {
    async publishCommentFn () {
      // loading加载提示
      this.$toast.loading({
        duration: 0, // 持续展示 toast
        message: '加载中...',
        forbidClick: true
      })
      // 发送请求
      try {
        const { data: res } = await publishComment({
          target: this.target + '',
          content: this.message,
          art_id: this.artId ? (this.artId + '') : this.artId
        })
        // 追加一个属性
        res.data.new_obj.is_liking = false
        // 把服务器返回的数据 传给父组件进行追加 视图更新
        this.$emit('onPostSuccess', res.data.new_obj)
        // 清空input内容
        this.message = ''
        this.$toast('发布成功')
      } catch (err) {
        this.$toast('发布失败')
      }
    }
  }
}
</script>

<style scoped lang="less">
.comment-post {
  display: flex;
  align-items: center;
  padding: 32px 0 32px 32px;
  .post-field {
    background-color: #f5f7f9;
  }
  .post-btn {
    width: 150px;
    border: none;
    padding: 0;
    color: #6ba3d8;
    &::before {
      display: none;
    }
  }
}
</style>
